package org.KeyCrafter.util;

import java.text.DecimalFormat;

public class ProgressBar {
    // 总数
    private long total;
    // 标题
    private String title = "Progress";
    // 进度条长度
    private int barLen = 50;
    //用于进度条显示的字符
    private char showChar = '#';
    // 进度格式
    private DecimalFormat formater = new DecimalFormat("#.##%");

    public ProgressBar(long total, int barLen, char showChar) {
        this.total = total;
        this.barLen = barLen;
        this.showChar = showChar;
    }

    /**
     * 显示进度条
     */
    public void show(long loaded) {
        // 光标移至行首
        reset();
        // 比例
        float rate = (float) (loaded * 1.0 / total);
        // 比例*进度条总长度=当前长度
        draw(barLen, rate);
        if (loaded == total) {
            afterComplete();
        }
    }

    private static final char BACK_GROUND = '░';
    StringBuilder stringBuilder = new StringBuilder();
    // 有背景的进度条
    public void showWithBackground() {

    }

    /**
     * 画指定长度个showChar
     */
    private void draw(int barLen, float rate) {
        int len = (int) (rate * barLen);
        System.out.print(title + ": ");
        for (int i = 0; i < len; i++) {
            System.out.print(showChar);
        }
        for (int i = 0; i < barLen - len; i++) {
            System.out.print(" ");
        }
        System.out.print(" |" + format(rate));
    }

    /**
     * 光标移动到行首
     */
    private void reset() {
        System.out.print('\r');
    }

    /**
     * 完成后换行
     */
    private void afterComplete() {
        System.out.print('\n');
    }

    // 强制完成
    public void forceComplete() {
        show(this.total);
    }

    // 将浮点数返回字符串
    private String format(float num) {
        return formater.format(num);
    }
}
